<template>
  <div class="box">
    <!-- 聊天容器 -->
    <header>
      <van-nav-bar title="咨询医生" left-arrow @click-left="onClickLeft" />
    </header>
    <main>
      <div class="center">
        <!-- 显示在线人数 -->
        <p style="color: #ccc">实时在线人数：{{ onlineList.length }}</p>

        <div class="loaction">
          <div class="message-item" v-for="(item, index) in messageList" :key="index">
            <div class="flex-left" v-if="item.userId !== userInfo.userId">
              <div class="avatar">
                <div class="userimage">
                </div>
                <div class="pass">
                  <img :src="images" alt="" />
                </div>
              </div>
              <div style="margin-left: 10px" class="message-content">
                <div v-if="item.content.startsWith('data:image')">
                  <img :src="item.content" class="uploaded-image" />
                </div>
                <div v-else>
                  {{ item.content }}
                </div>
              </div>
            </div>
            <!-- 如果是当前用户的消息，则显示在右边 -->
            <div v-else class="flex-right">
              <div class="message-content" style="margin-right: 10px">
                <div v-if="item.content.startsWith('data:image')">
                  <img :src="item.content" class="uploaded-image" />
                </div>
                <div v-else>
                  {{ item.content }}
                </div>
              </div>
              <div class="avatar">
                <div class="userimage">
                </div>
                <div class="pass">
                  <img :src="images" alt="" />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="send-box">
          <van-icon name="smile-o" class="smile-icon" @click="toggleEmojis" />
          <div v-if="isEmojisVisible" class="emoji-selector">
            <div class="emoji-item" v-for="emoji in emojis" :key="emoji" @click="addEmoji(emoji)">
              {{ emoji.src }}
            </div>
          </div>
          <van-icon name="photo" class="photo-icon" @click="triggerFileInput" />
          <input type="file" ref="fileInput" @change="handleImageUpload" style="display: none" />
          <input
            class="message-input"
            type="text"
            v-model="yourMessage"
            @keyup.enter="sendMessage"
            placeholder="请在此输入病情......"
          />

          <button class="send-btn" @click="sendMessage">发送</button>
          <van-icon name="add" class="add-icon" @click="qbz" />
        </div>
      </div>
      <div class="op" v-if="isVisible"></div>
    </main>

    <footer>
      <div class="icon">
        <van-icon name="todo-list" class="icon-todo" @click="triggerFileInput" />
        <van-icon name="cluster" class="icon-list" @click="showPopup" />
        <van-icon name="volume" class="icon-vue" @click="toggleVolumePanel" />
      </div>
      <div class="spass">
        <span>发送文件</span>
        <span>服务评价</span>
        <span>声音控制</span>
      </div>

      <!-- <van-popup v-model:show="show" position="bottom" class="popup">
        <div class="first">
          <h3>服务评价</h3>
          <button @click="show = false">X</button>
        </div>
        <div class="second">
          <img src="../../../src/img/pj.png" alt="" />
          <van-rate
            v-model="value"
            :size="150"
            color="#FFB800"
            void-icon="star"
            void-color="#eee"
            class="star"
          />
          <div class="feedback-text">
            <span>{{ feedbackText }}</span>
          </div>
          <input
            type="text"
            placeholder="您认为我们还有哪些不足，请留下您的宝贵意见"
            style="padding: 30px"
          />
          <button @click="show = false">提交评价</button>
        </div>
      </van-popup> -->

      <div v-if="isVolumePanelVisible" class="volume-panel">
        <div class="volume-slider-container">
          <input
            type="range"
            v-model="volume"
            min="0"
            max="100"
            step="1"
            class="volume-slider"
            @input="updateVolume"
          />
        </div>
        <button class="close-btn" @click="toggleVolumePanel">关闭</button>
      </div>
    </footer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'

const isVisible = ref(false)
const qbz = () => {
  isVisible.value = !isVisible.value
}
const show = ref(false)
const showPopup = () => {
  show.value = true
}
const images = ref(
  'https://img2.baidu.com/it/u=2144393177,2431469631&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1736010000&t=3049f1710dd3d5fc3cbd87a6a94efd4b'
)
// 星星
const value = ref(0)
const feedbackText = computed(() => {
  switch (value.value) {
    case 1:
      return '差评'
    case 2:
      return '一般般'
    case 3:
      return '良好'
    case 4:
      return '满意'
    case 5:
      return '非常满意'
    default:
      return '' // 默认没有选择时的文本
  }
})
// 音量
const volume = ref(50)
const isVolumePanelVisible = ref(false)
const toggleVolumePanel = () => {
  isVolumePanelVisible.value = !isVolumePanelVisible.value
}
const updateVolume = () => {
  console.log(`当前音量${volume.value}`)
}

// 存储用户信息，初始化为一个空对象
const userInfo = ref({
  userId: '',
})

// 存储当前输入的消息
const yourMessage = ref('')

// 存储所有消息的列表
const messageList = ref([])

// 存储在线用户列表
const onlineList = ref([])

// WebSocket实例
let ws = null

// 获取文件输入框的引用
const fileInput = ref(null)

// 表情包选择器
const isEmojisVisible = ref(false)
const emojis = ref([
  { src: '😘', name: '恭喜' },
  { src: '😊', name: '笑脸' },
  { src: '😂', name: '大笑' },
  { src: '😍', name: '心心' },
  { src: '😎', name: '酷' },
  +{ src: '😅', name: '汗' },
  { src: '🥺', name: '难过' },
  { src: '😭', name: '伤心' },
  { src: '🙃', name: '惊讶' },
  { src: '😜', name: '酷炫' },
  { src: '🥳', name: '祝福' },
  { src: '😀', name: '微笑' },
  { src: '😁', name: '脸红' },
  { src: '😉', name: '开心' },
  { src: '😗', name: '亲亲' },
  { src: '😙', name: '嘴角' },
  { src: '😚', name: 'kiss' },
  { src: '🤗', name: '调皮' },
  { src: '🤔', name: '思考' },
  { src: '🤨', name: '抓狂' },
  { src: '😐', name: '无语' },
  { src: '😑', name: '呆' },
  { src: '😶', name: '困' },
  { src: '🙄', name: '鄙视' },
  { src: '🤐', name: '惊恐' },
  { src: '🤫', name: '骚扰' },
  { src: '🤥', name: '心碎' },
  { src: '😏', name: '笑' },
  { src: '😣', name: '难过' },
  { src: '😥', name: '心疼' },
  { src: '😮', name: '惊吓' },
  { src: '🤐', name: '惊恐' },
  { src: '😯', name: '惊讶' },
  { src: '😪', name: '困' },
  { src: '😴', name: '睡着' },
  { src: '😌', name: '生气' },
  { src: '😛', name: '生气' },
  // 可以添加更多表情包的 URL
])

// 切换表情包选择器的显示
const toggleEmojis = () => {
  isEmojisVisible.value = !isEmojisVisible.value
}

// 将表情包添加到输入框
const addEmoji = (emoji) => {
  yourMessage.value += `${emoji.src}`
  isEmojisVisible.value = false // 选择表情后关闭表情包选择器
}

// 触发文件输入框的点击事件
const triggerFileInput = () => {
  fileInput.value.click()
}

// 处理图片上传
const handleImageUpload = async (event) => {
  const file = event.target.files[0] // 获取上传的文件
  if (file && file.type.startsWith('image')) {
    const reader = new FileReader()
    reader.onloadend = () => {
      // 读取完毕后，将图片的Base64数据添加到消息
      const imageBase64 = reader.result
      sendImageMessage(imageBase64)
    }
    reader.readAsDataURL(file) // 将图片转换为Base64
  } else {
    alert('请选择一个图片文件')
  }
}

// 发送图片消息
const sendImageMessage = (imageBase64) => {
  // 发送图片数据到 WebSocket 服务器
  ws.send(
    JSON.stringify({
      type: 'message', // 消息类型
      userId: userInfo.value.userId, // 发送者ID
      content: imageBase64, // 发送的图片Base64编码
    })
  )
}

// 发送文本消息
const sendMessage = () => {
  if (yourMessage.value) {
    const message = {
      type: 'message', // 消息类型
      userId: userInfo.value.userId, // 发送者ID
      content: yourMessage.value, // 消息内容
    }

    // 发送消息到 WebSocket 服务器
    ws.send(JSON.stringify(message))

    // 将消息存储到本地存储
    const storedMessages = JSON.parse(localStorage.getItem('messages') || '[]')
    storedMessages.push(message)
    localStorage.setItem('messages', JSON.stringify(storedMessages))

    yourMessage.value = '' // 清空输入框
  }
}

// 初始化WebSocket连接的方法
const initWebsocket = () => {
  ws = new WebSocket('ws://localhost:8888/')
  console.log(ws)

  ws.onopen = () => {
    console.log('websocket连接成功')
    ws.send(
      JSON.stringify({
        type: 'init', // 初始化类型
        userId: userInfo.value.userId, // 用户ID
        content: '欢迎来到聊天室',
      })
    )
  }

  ws.onerror = () => {
    console.log('websocket连接失败')
  }

  ws.onmessage = (data) => {
    const message = JSON.parse(data.data)
    switch (message.type) {
      case 'tips':
        console.log(message.content)
        break
      case 'message':
        messageList.value.push(message)

        // 同步更新到 localStorage
        const storedMessages = JSON.parse(localStorage.getItem('messages') || '[]')
        storedMessages.push(message)
        localStorage.setItem('messages', JSON.stringify(storedMessages))
        break
      case 'onlineList':
        onlineList.value = message.list
        break
      default:
        break
    }
  }

  ws.onclose = () => {
    console.log('websocket连接关闭')
  }
}
// 时间戳
onMounted(() => {
  const storedMessages = JSON.parse(localStorage.getItem('messages') || '[]')
  messageList.value = storedMessages
  userInfo.value.userId = new Date().getTime().toString().slice(8)
  initWebsocket()
})
const onClickLeft = () => history.back()
</script>
<style lang="scss" scoped>
/* 全局样式重置 */
* {
  padding: 0;
  margin: 0;
  list-style: none;
  box-sizing: border-box;
}

/* 页面最外层容器，居中显示 */
.box {
  width: 100vw;
  height: 100vh;
  flex-direction: column;
  display: flex;
  background-color: #f8f8f8;


  main {
    flex: 1;
    height: 80%;

    .center {
      width: 100%;
      height: 1010px;
      border-radius: 8px;
      margin-bottom: 500px;

      .loaction {
        height: calc(100% - 100px);
        padding: 10px;
        box-sizing: border-box;
        overflow: auto;

        /* 每条消息项 */
        .message-item {
          width: 100%;
          margin: 0 auto;
          margin-bottom: 15px;
        }

        /* 消息居左显示（其他用户的消息） */
        .flex-left {
          display: flex;
          justify-content: flex-start;
        }

        /* 消息居右显示（当前用户的消息） */
        .flex-right {
          display: flex;
          justify-content: flex-end;
        }

        /* 用户头像样式 */
        .avatar {
          height: 100px;
          line-height: 100px;
          border-radius: 50%;
          overflow: hidden;
          background-color: #e5e6e8;
          min-width: 100px;
          display: flex;
           margin:0 20px;
          // 头像
          .userimage {
            opacity: 0;
          }

          .pass {
            height: 100px;
            line-height: 100px;
            border-radius: 50%;
            overflow: hidden;
            background-color: #e5e6e8;
            min-width: 100px;
            display: flex;
          }
        }

        /* 消息内容样式 */
        .message-content {
          min-height: 50px;
          background-color: #007bff;
          color: #fff;
          border-radius: 20px;
          padding: 10px;
          line-height: 60px;
          margin: 10px;
        }
      }

      /* 发送框的样式 */
      .send-box {
        height: 125px;
        display: flex;
        justify-content: space-around;
        // background-color: green;
        background-color: #fff;

        /* 消息输入框样式 */
        .message-input {
          height: 70px;
          width: 80%;
          line-height: 70px;
          // border: none;
          background-color: #f2f2fa;
          border-radius: 50px;
          margin-top: 25px;
          padding: 20px;
          border: none;
        }

        /* 发送按钮样式 */
        .send-btn {
          width: 150px;
          height: 70px;
          line-height: 60px;
          text-align: center;
          border: none;
          border-radius: 50px;
          margin-left: -142px;
          opacity: 0;
        
        }

        .add-icon {
          font-size: 50px;
          margin: 30px 20px;
          
        }

        .photo-icon {
          font-size: 50px;
          margin: 25px 20px;
        }

        .add-icon {
          line-height:70px;
          font-size: 50px;
          margin: 25px 20px;
        }
      }

      // 表情包按钮
      .smile-icon {
        top: 80.6%;
        left: 80%;
        position: absolute;
        font-size: 40px;
        z-index: 5;
      }

      // 表情包里
      .emoji-selector {
        width: 500px;
        height: 500px;
        background-color: pink;
        position: absolute;
        top: 86%;
        z-index: 2;
        width: 100%;
        height: 190px;

        .emoji-item {
          text-align: center;
          float: left;
          background-color: #f2f2fa;
          width: 125px;
          line-height: 70px;
          font-size: 35px;
        }
      }
    }

    .op {
      width: 100%;
      height: 190px;
      background-color: #f6f6f6;
      position: absolute;
      top: 86%;
      z-index: 1;
    }

    .uploaded-image {
      max-width: 250px;
      max-height: 250px;
      margin-top: 10px;
    }
  }

  footer {
    height: 150px;

    .spass {
      display: flex;
      justify-content: space-around;
      font-size: 24px;
      margin: 10px 5px;
    }

    .icon {
      display: flex;
      justify-content: space-around;

      .icon-todo {
        font-size: 50px;
        background-color: #f2f2fa;
        border-radius: 50px;
        width: 100px;
        border: 1px solid #ccc;
        text-align: center;
        height: 100px;
        line-height: 100px;
      }

      .icon-list {
        font-size: 50px;
        background-color: #f2f2fa;
        border-radius: 50px;
        width: 100px;
        border: 1px solid #ccc;
        text-align: center;
        height: 100px;
        line-height: 100px;
      }
      .icon-list{
         font-size: 50px;
         background:#f2f2fa; 
         width: 100px;
         border: 1px solid #ccc;
         text-align: center;
         height: 100px;
         line-height: 100px;
      }
      .icon-vue {
        font-size: 50px;
        background-color: #f2f2fa;
        border-radius: 50px;
        width: 100px;
        border: 1px solid #ccc;
        text-align: center;
        height: 100px;
        line-height: 100px;
      }
    }

    .popup {
      border-radius: 25px;
      height: 80%;

      .first {
        display: flex;
        justify-content: space-between;

        h3 {
          margin: 20px 20px;
        }

        button {
          width: 100px;
          height: 40px;
          margin: 20px 20px;
          background-color: #fffbe8;
          border: none;
          font-size: 24px;
        }

        background-color: #fffbe8;
      }

      .second {
        // background-color: green;
        img {
          width: 80%;
          height: 270px;
          margin: 50px 75px;
        }

        .star {
          margin: -30px 110px;
          padding: 0px 20px;
        }

        .app {
          text-align: center;
          padding: 20px;
        }

        .star {
          margin-bottom: 20px;
        }

        .feedback-text {
          font-size: 40px;
          color: #ffb800;
          margin-left: 300px;
        }

        input {
          width: 500px;
          height: 300px;
          margin-left: 130px;
          margin-top: 20px;
          border-radius: 50px;
          border: none;
          background-color: #f2f2fa;
        }

        button {
          width: 500px;
          height: 80px;
          background-color: #fffbe8;
          border-radius: 50px;
          margin-top: 30px;
          margin-left: 130px;
          border: none;
          border: 1px solid #ccc;
        }
      }
    }

    /* 音量面板样式 */
    .volume-panel {
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      background-color: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.5);

      /* 音量滑动条样式 */
      .volume-slider-container {
        width: 80%;
        margin-bottom: 20px;
      }

      .volume-slider {
        width: 100%;
        -webkit-appearance: none;
        appearance: none;
        height: 20px;
        background: #ccc;
        border-radius: 50px;
        outline: none;
        transition: background 0.5s ease;
      }

      .volume-slider:hover {
        background: #007bff;
      }

      /* 关闭按钮样式 */
      .close-btn {
        background-color: #dc3545;
        color: white;
        padding: 10px 15px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 20px;
      }

      .popup-tou {
        width: 86%;
        height: 200px;
        margin-left: 7%;
        border-radius: 10px;
        text-align: center;
        margin-top: 500px;
        font-size: 30px;
      }

      .popup-tou > p {
        height: 100px;
        line-height: 100px;
      }
    }

    /* 小屏幕下的样式优化 */
    @media (max-width: 768px) {
      .volume-btn {
        font-size: 20px;
      }

      .volume-slider {
        height: 8px;
      }

      .close-btn {
        font-size: 6px;
      }
    }
  }
}
</style>